package com.zhongxi.guoyuan.utils;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;

import com.zhongxi.guoyuan.OffLineShop.ConnectNet.NetWork;
import com.zhongxi.guoyuan.OffLineShop.UI.OffLineShopDetailActivtiy;
import com.zhongxi.guoyuan.OffLineShop.UrlOffLine.RelativeUrl;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.view.AdActivity;
import com.zhongxi.guoyuan.view.MainHomeActivity;
import com.zhongxi.guoyuan.view.PlayActivity;
import com.zhongxi.guoyuan.view.beautifulStore.ProjectDetailActivity;
import com.zhongxi.guoyuan.view.beautifulStore.StoreDetailActivity;
import com.zhongxi.guoyuan.view.personalCenter.ClearWeedDetailActivity;
import com.zhongxi.guoyuan.view.rewardCoin.RewardCoinDetailActivity;
import com.zhongxi.guoyuan.view.rewardCoin.RewardCoinShoperAtivity;
import com.zhongxi.guoyuan.view.user.gift.GiftDetailActivity;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Administrator on 2018/2/3.
 */

public class LunBoUtils {

    private Context context;

    private static LunBoUtils instance;
    private ProgressDialog mProgressDialog;

    private LunBoUtils(Context context) {
        this.context = context;
    }


    public static LunBoUtils getInstance(Context context) {
        if (instance == null) {
            instance = new LunBoUtils(context);
        }
        return instance;
    }

    public void lunBoItemClickListener(String adsid, final int position, final String url) {
        NetWork.getOffLineApi().adClickListener(RelativeUrl.CLICKADS + MyApplication.getInstance().getUrl(),
                MyApplication.getInstance().getCheck(false), adsid)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showProgressDialog();
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<BaseResponse>() {
                    @Override
                    public void accept(BaseResponse baseResponse) throws Exception {
                        dismessProgressDialog();
                        MyApplication.getInstance().setSpValue(baseResponse.getSafeobj());
                        if (baseResponse.getCode() == 1) {
                            goinAdItem(position, url);
                        } else if (baseResponse.getCode() == 2816) {
                            logoutDialog();
                        } else {
                            ToastUtil.show(context.getString(R.string.loseData, baseResponse.getCode()));
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        dismessProgressDialog();
                        ToastUtil.show(context.getString(R.string.load_error));
                    }
                });

    }

    private void goinAdItem(int position, String url) {
        if (!TextUtils.isEmpty(url)) {
            Uri uri = Uri.parse(url);
            if (position == 0) {
                String protocol = uri.getScheme();
                String server = uri.getAuthority();
                String path = uri.getPath();
                String id = uri.getQueryParameter("id");
                if ("inner".equals(protocol)) {
                    if ("beauty.item".equals(server)) {   //美容项目
                        Intent intent = new Intent(context, ProjectDetailActivity.class);
                        intent.putExtra("id", id);
                        context.startActivity(intent);
                    } else if ("beauty.store".equals(server)) {  //美容店铺
                        Intent intent = new Intent(context, StoreDetailActivity.class);
                        intent.putExtra("shopid", id);
                        context.startActivity(intent);
                    } else if ("market.goods".equals(server)) {  //超市商品
                        Intent intent = new Intent(context, RewardCoinDetailActivity.class);
                        intent.putExtra("gid", id);
                        context.startActivity(intent);
                    } else if ("market.store".equals(server)) {   //超市店铺
                        Intent shopCarIntent = new Intent(context, RewardCoinShoperAtivity.class);
                        shopCarIntent.putExtra("shopid", id);
                        context.startActivity(shopCarIntent);
                    } else if ("activity.share".equals(server)) {   //活动分享
                        Intent intent = new Intent(context, GiftDetailActivity.class);
                        intent.putExtra("aid", id);
                        context.startActivity(intent);
                    } else if ("offline.shop".equals(server)) {
                        Intent mIntent = new Intent(UiUtils.getContext(), OffLineShopDetailActivtiy.class);
                        mIntent.putExtra("offlineshopid", id);
                        context.startActivity(mIntent);
                    } else if ("inner.goods".equals(server)) {
                        Intent intent = new Intent(UiUtils.getContext(), ClearWeedDetailActivity.class);
                        intent.putExtra("id", id);
                        context.startActivity(intent);
                    }
                } else {
                    Intent intent = new Intent(context, AdActivity.class);
                    intent.putExtra("url", uri.toString());
                    context.startActivity(intent);
                }
            } else {
                Intent intent = new Intent(context, PlayActivity.class);
                intent.putExtra("url", uri.toString());
                context.startActivity(intent);
            }
        }
    }


    private void logoutDialog() {
        final AlertDialog mDialog = new AlertDialog.Builder(context).create();
        View view = UiUtils.inflate(R.layout.dialog_logout);
        TextView tv_Iknow = (TextView) view.findViewById(R.id.tv_Iknow);
        tv_Iknow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
                clearData();
            }
        });
        mDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (mDialog != null && mDialog.isShowing()) {
                        mDialog.dismiss();
                        clearData();
                    }
                    return true;
                }
                return false;
            }
        });
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.setView(view);
        mDialog.show();
    }

    private void clearData() {
        if (null != MyApplication.getInstance().getUserId() || !"".equals(MyApplication.getInstance().getUserId())) {
            MyApplication.getInstance().sharedPrefrences.edit().putString("phone", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("userid", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("username", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("shopname", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rmb", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("silver", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("inner", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("hd", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("num", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("avatar", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putBoolean("shareHolder", false).commit();
            MyApplication.getInstance().sharedPrefrences.edit().putBoolean("privilege", false).commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("avatar", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rewardName", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rewardUserphone", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddress", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddressid", "").commit();
            SpUtils.getInstance().saveSp("shopid", "");
            SpUtils.getInstance().saveSp("mdffline", "");
            SpUtils.getInstance().saveSp("orderid", "");
            context.startActivity(new Intent(context, MainHomeActivity.class));
        }
    }

    protected void showProgressDialog() {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(context, R.style.CustomProgressDialog);
        }
        mProgressDialog.setMessage("加载中....");
        mProgressDialog.setIndeterminateDrawable(context.getResources().getDrawable(R.drawable.progressbarstyle_large));
        mProgressDialog.show();
    }

    protected void dismessProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

}
